package com.yehun.admin.controller;

import com.yehun.admin.models.JsonResult;
import com.yehun.admin.models.PageConfig;
import com.yehun.admin.models.UserModel;
import com.yehun.entity.PagerEntity;
import com.yehun.entity.Role;
import com.yehun.entity.Route;
import com.yehun.entity.User;
import com.yehun.enums.StatusEnum;
import com.yehun.enums.UserTypeEnum;
import com.yehun.exception.ErrorException;
import com.yehun.service.RoleService;
import com.yehun.service.RouteService;
import com.yehun.service.UserService;
import com.yehun.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Controller
@RequestMapping(value = "user")
@Component("AdminUserController")
public class UserController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    private final RoleService roleService;
    private final UserService userService;
    private final RouteService routeService;

    @Autowired
    public UserController(RoleService roleService, UserService userService, RouteService routeService) {
        this.roleService = roleService;
        this.userService = userService;
        this.routeService = routeService;
    }

    @RequestMapping(value = {"", "index", "list"}, name = "用户列表")
    public String list() {
        return "user/list";
    }

    @ResponseBody
    @RequestMapping(value = "listAjax", name = "用户列表Ajax")
    public PageConfig<User> listAjax() {
        int pageIndex = ParamUtils.getPageIndex();
        int pageSize = ParamUtils.getPageSize();
        PagerEntity<User> pager = userService.listPager(pageIndex, pageSize);
        return PageConfig.mapper(pager);
    }

    @RequestMapping(value = "add", method = RequestMethod.GET, name = "用户添加")
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("user/add");
        view.addObject("types", EnumUtils.getSelect(UserTypeEnum.class));
        view.addObject("statuses", EnumUtils.getSelect(StatusEnum.class));
        return view;
    }

    @ResponseBody
    @RequestMapping(value = "addAjax", method = RequestMethod.POST, name = "用户添加Post")
    public JsonResult add(UserModel userModel) {
        JsonResult jsonResult = new JsonResult();
        logger.info("userModel={}", JsonUtils.serialize(userModel));
        User user = userModel.mapper();
        logger.info("userEntity={}", JsonUtils.serialize(user));
        try {
            user.setUserId(UUID.randomUUID().toString());
            user.setToken(UUID.randomUUID().toString());
            user.setRoleId(0);
            int row = userService.save(user);
            boolean ret = row > 0;
            jsonResult.setCode(ret ? 0 : 1);
            jsonResult.setMessage(ret ? "添加成功" : "添加失败");
        } catch (ErrorException e) {
            logger.error("添加用户异常", e);
            jsonResult.setCode(-1);
            jsonResult.setMessage(e.getMessage());
        }
        return jsonResult;
    }

    @RequestMapping(value = "editInfo", method = RequestMethod.GET, name = "用户信息修改")
    public ModelAndView editInfo(String userId) {
        ModelAndView view = new ModelAndView("user/editInfo");
        view.addObject("types", EnumUtils.getSelect(UserTypeEnum.class));
        view.addObject("statuses", EnumUtils.getSelect(StatusEnum.class));
        User user = userService.getByUserId(userId);
        view.addObject("user", user);
        return view;
    }

    @ResponseBody
    @RequestMapping(value = "editInfo", method = RequestMethod.POST, name = "用户信息修改post")
    public JsonResult editInfo(UserModel user) {
        JsonResult jsonResult = new JsonResult();
        logger.info("user.editInfo, user={}", JsonUtils.serialize(user));
        return jsonResult;
    }

    @RequestMapping(value = "editPassword", method = RequestMethod.GET, name = "用户密码修改")
    public ModelAndView editPassword(String userId) {
        ModelAndView view = new ModelAndView("user/editPassword");
        User user = userService.getByUserId(userId);
        view.addObject("user", user);
        return view;
    }

    @RequestMapping(value = "editPermission", method = RequestMethod.GET, name = "用户权限修改")
    public ModelAndView editPermission(String userId) {
        ModelAndView view = new ModelAndView("user/editPermission");
        User user = userService.getByUserId(userId);
        view.addObject("user", user);
        List<Route> routes = routeService.listAll();
        List<Map<String, Object>> mapList = new LinkedList<>();
        Map<String, Object> map;
        for (Route route : routes) {
            if (StringUtils.isEmpty(route.getRemark())) continue;
            map = new LinkedHashMap<>();
            map.put("url", route.getUrl());
            map.put("remark", route.getRemark());
            map.put("value", route.getValue());
            map.put("checked", BitOperUtils.exists(user.getPermission(), route.getValue()));
            mapList.add(map);
        }
        view.addObject("permissions", mapList);
        List<Role> roles = roleService.listAll();
        view.addObject("roles", roles);
        return view;
    }

    @ResponseBody
    @RequestMapping(value = "editPermission", method = RequestMethod.POST, name = "用户权限修改post")
    public JsonResult editPermission(@RequestParam("userId") String userId, @RequestParam("roleId") int roleId, @RequestParam("values[]") String[] values) {
        logger.info("userId={}", userId);
        logger.info("values.length={}", values.length);
        Long userValue = 0L;
        Long tmpValue;
        for (String value : values) {
            tmpValue = ParseUtils.parseLong(value);
            if (!BitOperUtils.exists(userValue, tmpValue)) {
                userValue = BitOperUtils.insert(userValue, tmpValue);
            }
        }
        logger.info("userValue={}", userValue);
        JsonResult jsonResult = new JsonResult();
        try {
            int row = userService.updatePermission(userId, roleId, userValue);
            boolean ret = row > 0;
            jsonResult.setCode(ret ? 0 : 1);
            jsonResult.setMessage(ret ? "修改成功" : "修改失败");
        } catch (ErrorException e) {
            logger.error("用户修改权限异常", e);
            jsonResult.setCode(-1);
            jsonResult.setMessage(e.getMessage());
        }
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping(value = "remove", name = "用户删除")
    public JsonResult remove() {
        Integer[] idArray = ParamUtils.getIntArray("idArray", ",");
        logger.info("idArray.length={}", idArray.length);
        JsonResult jsonResult = new JsonResult();
        try {
            int row = userService.remove(idArray);
            boolean ret = row > 0;
            jsonResult.setCode(ret ? 0 : 1);
            jsonResult.setMessage(ret ? "删除成功" : "删除失败");
        } catch (ErrorException e) {
            jsonResult.setCode(-1);
            jsonResult.setMessage(e.getMessage());
        }
        return jsonResult;
    }

}
